<template>
  <div class="new-songs">
    <!-- 组件标题 -->
    <div class="section-header">
      <h2>最新音乐</h2>
      <div class="section-meta">
        <span>共 {{ songsData.total }} 首歌曲</span>
      </div>
    </div>

    <!-- 歌曲列表 -->
    <el-table :data="displaySongs" style="width: 100%" class="song-table">
      <!-- 序号列 -->
      <el-table-column label="序号" width="60" align="center">
        <template #default="scope">
          <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>

      <!-- 封面列 -->
      <el-table-column label="封面" width="60">
        <template #default="scope">
          <div class="cover-container">
            <img
              :src="scope.row.coverUrl || '/images/default_music_cover.png'"
              alt="歌曲封面"
              class="song-cover"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 歌曲信息列 -->
      <el-table-column label="歌曲" min-width="100">
        <template #default="scope">
          <div class="song-info" @click="handleItemClick(scope.row)">
            <div class="song-name">{{ scope.row.songName }}</div>
            <div
              class="song-artist"
              style="cursor: pointer"
              @click.stop="goToSingerDetail(scope.row)"
            >
              {{ scope.row.artistName }}
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 专辑列 -->
      <el-table-column label="专辑" min-width="100">
        <template #default="scope">
          <router-link
            v-if="scope.row.albumId"
            :to="{
              name: 'AlbumDetails',
              params: { albumId: scope.row.albumId },
              query: { from: $route.fullPath },
            }"
            style="cursor: pointer; color: inherit; text-decoration: none"
          >
            {{ scope.row.albumName }}
          </router-link>
          <span v-else>未收录专辑</span>
        </template>
      </el-table-column>

      <!-- 时长列（带悬停效果） -->
      <el-table-column label="时长" width="200" align="left">
        <template #default="scope">
          <div
            class="duration-container"
            @mouseenter="showHoverInfo(scope.row)"
            @mouseleave="hideHoverInfo"
          >
            <span class="duration">{{
              formatDuration(scope.row.duration)
            }}</span>
            <div v-if="hoverSong === scope.row" class="duration-tooltip">
              <div class="tooltip-item">
                播放次数: {{ formatPlayCount(scope.row.playCount) }}
              </div>
              <div class="tooltip-item">ID: {{ scope.row.songId }}</div>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 操作按钮列 - 更新图标 -->
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <div class="action-buttons">
            <el-button size="small" @click="handlePlay(scope.row)" circle>
              <el-icon><VideoPlay /></el-icon>
            </el-button>
            <el-button
              size="small"
              @click="showPlaylistDialog(scope.row)"
              circle
            >
              <el-icon><FolderAdd /></el-icon>
            </el-button>
            <el-button size="small" @click="handleCollect(scope.row)" circle>
              <el-icon v-if="scope.row.isCollected"><StarFilled /></el-icon>
              <el-icon v-else><Star /></el-icon>
            </el-button>
            <el-button size="small" @click="shareSong(scope.row)" circle>
              <el-icon><Share /></el-icon>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        background
        layout="prev, pager, next"
        :current-page="currentPage"
        :page-size="pageSize"
        :total="songsData.total"
        @current-change="handlePageChange"
      />
    </div>

    <!-- 歌单选择弹窗 -->
    <el-dialog
      title="选择歌单"
      :visible.sync="playlistDialogVisible"
      width="400px"
      center
    >
      <div v-if="userPlaylists.length > 0">
        <div
          v-for="playlist in userPlaylists"
          :key="playlist.playlistId"
          class="playlist-item"
          @click="addToSelectedPlaylist(playlist)"
        >
          <img
            :src="playlist.coverUrl || '/images/default_playlist_cover.png'"
            class="playlist-cover"
            alt="歌单封面"
          />
          <div class="playlist-info">
            <div class="playlist-name">{{ playlist.playlistName }}</div>
            <div class="playlist-count">{{ playlist.songCount }} 首</div>
          </div>
        </div>
      </div>
      <div v-else class="no-playlists">您还没有创建任何歌单</div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="playlistDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="createNewPlaylist"
          >新建歌单</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { useStore } from 'vuex';
import eventBus, { EventType } from "@/utils/eventBus.js";
import {
  FolderAdd,
  Share,
  Star,
  StarFilled,
  VideoPlay,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import api from "../services/api"; // 导入API模块

export default {
  name: "NewSongs",
  components: {
    VideoPlay,
    FolderAdd,
    Star,
    StarFilled,
    Share,
  },
  // 移除 setup，全部用 data/options API，避免 userId 报错
  data() {
    return {
      songsData: {
        total: 0,
        songs: [],
      },
      hoverSong: null,
      tooltipTimer: null,
      currentPage: 1,
      pageSize: 10,
      playlistDialogVisible: false,
      selectedSong: null,
      userPlaylists: [],
      userId: null, // 新增 userId，避免 setup 阶段报错
    };
  },
  computed: {
    // 移除 total 计算属性，直接用 songsData.total
    displaySongs() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.songsData.songs.slice(start, end);
    },
  },
  async created() {
    // 尝试从 localStorage 或 window 全局获取 userId，避免 setup 阶段报错
    try {
      const user =
        this.$store && this.$store.state && this.$store.state.user
          ? this.$store.state.user
          : null;
      this.userId = user && user.userId ? user.userId : null;
    } catch (e) {
      console.error("获取用户ID失败:", e);
      this.userId = null;
    }
    await this.fetchLatestSongs();
    if (this.userId) {
      await this.fetchUserPlaylists();
    }
  },
  methods: {
    // 跳转到歌手详情，并传递 from 参数
    goToSingerDetail(song) {
      if (song && song.artistId) {
        this.$router.push({
          name: "SingerDetail",
          params: { id: song.artistId },
          query: { from: this.$route.fullPath },
        });
      }
    },
    // 获取最新歌曲
    async fetchLatestSongs() {
      try {
        // 调用后端API获取最新歌曲，参数为 limit
        const response = await api.musicApi.getNewSongs({
          limit: this.pageSize,
        });

        if (response.code === 200 && Array.isArray(response.data)) {
          this.songsData = {
            total: response.data.length,
            songs: response.data.map((song) => ({
              songId: song.songId,
              songName: song.songName,
              artistId: song.artistId,
              artistName: song.artistName || "未知艺术家",
              albumId: song.albumId || null,
              albumName: song.albumName || "未知专辑",
              duration: song.duration,
              coverUrl: song.coverUrl || "/images/default_music_cover.png",
              fileUrl: song.fileUrl,
              playCount: song.playCount || 0,
              genre: song.genre,
              language: song.language,
              releaseDate: song.releaseDate,
              fileSize: song.fileSize,
              bitRate: song.bitRate,
              format: song.format,
              isVip: song.isVip,
              isCollected: false,
            })),
          };

          // 如果用户已登录，获取收藏状态
          if (this.userId) {
            await this.fetchCollectionStatus();
          }
        } else {
          throw new Error(response.message || "获取最新歌曲失败");
        }
      } catch (error) {
        console.error("获取最新歌曲失败:", error);
        ElMessage.error("获取最新歌曲失败，请稍后重试");
      }
    },

    // 获取用户歌单
    async fetchUserPlaylists() {
      try {
        const response = await api.playlistApi.getUserPlaylists(this.userId, {
          page: 1,
          size: 10,
        });

        if (response.code === 200) {
          this.userPlaylists = response.data.list.map((playlist) => ({
            playlistId: playlist.playlistId,
            playlistName: playlist.name,
            coverUrl: playlist.coverUrl,
            songCount: playlist.songCount,
          }));
        }
      } catch (error) {
        console.error("获取用户歌单失败:", error);
      }
    },

    // 获取收藏状态
    async fetchCollectionStatus() {
      try {
        // 批量获取收藏状态
        const songIds = this.songsData.songs.map((song) => song.songId);
        const response = await api.collectionApi.checkCollectionStatusBatch({
          userId: this.userId,
          targetIds: songIds,
          targetType: "song",
        });

        if (response.code === 200) {
          const statusMap = response.data;
          this.songsData.songs = this.songsData.songs.map((song) => ({
            ...song,
            isCollected: statusMap[song.songId] || false,
          }));
        }
      } catch (error) {
        console.error("获取收藏状态失败:", error);
      }
    },

    // 显示歌单选择对话框
    showPlaylistDialog(song) {
      this.selectedSong = song;
      this.playlistDialogVisible = true;
    },

    // 添加到选中的歌单
    async addToSelectedPlaylist(playlist) {
      try {
        const response = await api.playlistApi.addSongsToPlaylist(
          playlist.playlistId,
          {
            songIds: [this.selectedSong.songId],
          }
        );

        if (response.code === 200) {
          ElMessage.success(`已添加到 ${playlist.playlistName}`);
          this.playlistDialogVisible = false;
        } else {
          throw new Error(response.message);
        }
      } catch (error) {
        console.error("添加到歌单失败:", error);
        ElMessage.error(`添加到歌单失败: ${error.message}`);
      }
    },

    // 新建歌单
    async createNewPlaylist() {
      try {
        this.$prompt("请输入歌单名称", "新建歌单", {
          confirmButtonText: "创建",
          cancelButtonText: "取消",
          inputPattern: /^.{2,20}$/,
          inputErrorMessage: "歌单名称长度应在2-20个字符之间",
        })
          .then(async ({ value }) => {
            const response = await api.playlistApi.createPlaylist({
              name: value,
              description: "",
              isPublic: true,
            });

            if (response.code === 200) {
              const newPlaylist = {
                playlistId: response.data.playlistId,
                playlistName: value,
                coverUrl: "/images/default_playlist_cover.png",
                songCount: 0,
              };

              this.userPlaylists.unshift(newPlaylist);
              ElMessage.success(`歌单 "${value}" 创建成功`);
            } else {
              throw new Error(response.message);
            }
          })
          .catch(() => {});
      } catch (error) {
        console.error("创建歌单失败:", error);
        ElMessage.error(`创建歌单失败: ${error.message}`);
      }
    },

    // 收藏歌曲
    async handleCollect(song) {
      try {
        if (song.isCollected) {
          // 取消收藏
          const response = await api.collectionApi.removeCollection(
            song.songId,
            "song"
          );

          if (response.code === 200) {
            song.isCollected = false;
            ElMessage.success(`已取消收藏 "${song.songName}"`);
          } else {
            throw new Error(response.message);
          }
        } else {
          // 添加收藏
          const response = await api.collectionApi.addCollection({
            targetId: song.songId,
            targetType: "song",
          });

          if (response.code === 200) {
            song.isCollected = true;
            ElMessage.success(`已收藏 "${song.songName}"`);
          } else {
            throw new Error(response.message);
          }
        }
      } catch (error) {
        console.error("收藏操作失败:", error);
        ElMessage.error(`操作失败: ${error.message}`);
      }
    },

    // 分享歌曲
    shareSong(song) {
      ElMessageBox.confirm(`分享歌曲 "${song.songName}" 给好友?`, "分享歌曲", {
        confirmButtonText: "复制链接",
        cancelButtonText: "取消",
        type: "info",
      }).then(() => {
        navigator.clipboard.writeText(
          `https://musicplatform.com/song/${song.songId}`
        );
        ElMessage.success("歌曲链接已复制到剪贴板");
      });
    },

    // 处理页码变化
    handlePageChange(page) {
      this.currentPage = page;
      this.fetchLatestSongs();
    },

    handleItemClick(song) {
      this.$emit("item-click", song);
    },

    // 处理歌曲播放
    async handlePlay(song) {
      try {
        // 先获取歌曲播放URL和播放令牌
        const response = await api.musicApi.playSong({
          songId: song.songId,
          playSource: "newSongs", // 播放源记录为新歌列表
          position: 0, // 从头开始播放
        });

        if (response.code === 200) {
          // 创建扩展的歌曲对象，包含播放所需的所有信息
          const playableSong = {
            ...song,
            playUrl: response.data.playUrl,
            playToken: response.data.playToken,
            expireTime: response.data.expireTime,
          };

          // 使用事件总线触发播放事件，并传递完整的歌曲信息
          eventBus.emit(EventType.PLAY_SONG, playableSong);

          // 同时保留原来的emit事件，兼容现有代码
          this.$emit("play", playableSong);

          // 可以添加播放成功的提示
          ElMessage.success(`正在播放: ${song.songName}`);
        } else {
          throw new Error(response.message || "获取播放信息失败");
        }
      } catch (error) {
        console.error("播放歌曲失败:", error);
        ElMessage.error(`播放失败: ${error.message || "未知错误"}`);
      }
    },

    showHoverInfo(song) {
      clearTimeout(this.tooltipTimer);
      this.tooltipTimer = setTimeout(() => {
        this.hoverSong = song;
      }, 300);
    },

    hideHoverInfo() {
      clearTimeout(this.tooltipTimer);
      this.hoverSong = null;
    },

    formatPlayCount(count) {
      if (count >= 100000000) {
        return (count / 100000000).toFixed(1) + "亿";
      }
      if (count >= 10000) {
        return (count / 10000).toFixed(1) + "万";
      }
      return count;
    },

    // 格式化歌曲时长
    formatDuration(seconds) {
      if (!seconds) return "00:00";
      const mins = Math.floor(seconds / 60);
      const secs = Math.floor(seconds % 60);
      return `${mins.toString().padStart(2, "0")}:${secs
        .toString()
        .padStart(2, "0")}`;
    },
  },
};
</script>

<style scoped>
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h2 {
  font-size: 24px;
  color: #333;
  font-weight: 600;
  position: relative;
  padding-left: 12px;
}

.section-header h2::before {
  content: "";
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
  height: 20px;
  width: 4px;
  background: #6b46c1;
  border-radius: 2px;
}

.section-meta {
  font-size: 14px;
  color: #666;
}

.song-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  border: none;
  margin-bottom: 20px;
}

.song-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

.song-table ::v-deep .el-table__row:hover {
  background-color: #f5f7ff;
}

.cover-container {
  display: flex;
  justify-content: center;
}

.song-cover {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
  transition: transform 0.3s ease;
}

.song-cover:hover {
  transform: scale(1.05);
}

.song-info {
  cursor: pointer;
  padding: 5px 0;
  transition: all 0.2s;
}

.song-info:hover {
  color: #6b46c1;
}

.song-name {
  font-weight: 500;
  font-size: 14px;
  margin-bottom: 4px;
}

.song-artist {
  font-size: 12px;
  color: #888;
}

.duration-container {
  position: relative;
  display: inline-block;
  padding: 5px 0;
}

.duration {
  display: block;
  text-align: right;
  padding-right: 10px;
}

.duration-tooltip {
  position: absolute;
  right: 0;
  top: 100%;
  margin-top: 5px;
  padding: 8px 12px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  width: 180px;
  z-index: 10;
  pointer-events: none;
  border: 1px solid #ebeef5;
}

.tooltip-item {
  font-size: 12px;
  line-height: 1.5;
}

.tooltip-item:first-child {
  margin-bottom: 4px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  align-items: center;
}

.action-buttons .el-button {
  background-color: #f5f7fa;
  border: none;
  transition: all 0.3s;
}

.action-buttons .el-button:hover {
  background-color: #6b46c1;
  color: white;
  transform: scale(1.1);
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

/* 歌单选择弹窗样式 */
.playlist-item {
  display: flex;
  align-items: center;
  padding: 10px;
  margin-bottom: 10px;
  border-radius: 6px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.playlist-item:hover {
  background-color: #f5f7ff;
}

.playlist-cover {
  width: 50px;
  height: 50px;
  border-radius: 4px;
  object-fit: cover;
  margin-right: 15px;
}

.playlist-info {
  flex: 1;
}

.playlist-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.playlist-count {
  font-size: 12px;
  color: #888;
}

.no-playlists {
  text-align: center;
  padding: 20px;
  color: #999;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
}

@media (max-width: 768px) {
  .song-table {
    font-size: 12px;
  }

  .song-cover {
    width: 40px;
    height: 40px;
  }

  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .section-header h2 {
    font-size: 20px;
  }

  .pagination-container {
    overflow-x: auto;
  }

  .action-buttons {
    gap: 5px;
  }

  .action-buttons .el-button {
    padding: 6px;
  }
}
</style>
